package com.beyond.core.codec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

import com.beyond.core.common.EscapeTool;

/**
 * 木牛雷达协议设置功能
 * 描述：
 * @author wangyingda
 * @date 2021年7月8日
 *
 */
public class SettingRadarProtocolMinistry {
	
/**
 * 封装完整的雷达协议	
 * @param Msgheader 
 * @param Msgbody
 * @return
 * @throws IOException
 */
public static byte[] setNetRadarMsg(byte[] Msgheader, byte[] Msgbody) throws IOException {
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ByteArrayOutputStream bosfinal = new ByteArrayOutputStream();
		
		bos.write(Msgheader);
		if (Msgbody != null) {
			bos.write(Msgbody);
		}
		
		byte[] turn = bos.toByteArray();
		//TODO 考虑校验位 
		int checksum = (int) getCRC32Checksum(turn);
		bos.write((byte) (checksum & 0x000000ff));
		bos.close();
		bosfinal.write((byte) 0x7e); //一个数字标识占位 整数129 16进制是0x7e
		bosfinal.write(EscapeTool.escapeData(turn)); //TODO 调用转义处理
		bosfinal.write((byte) 0x7e);
		byte[] returndata = bosfinal.toByteArray();
		bosfinal.close();		
		return returndata;
	}
/**
 * 发送下行指令，TODO 待完善
 * @param commandType
 * @return
 * @throws IOException
 */
 public static byte[] sendCommand(String commandType) throws IOException {
	 
	 ByteArrayOutputStream bos = new ByteArrayOutputStream();// 消息头+消息体
		/********开始拼装消息头********/
	 
		byte linkedAddr = 0 & 0xff;
		byte protocolversion = 0x10;  //协议版本号  
		byte opType = (byte) 0x81; //操作类型
		byte objectFlag = 0x02; //对象标识
		
		byte[] Msgheader = new byte[4];
		Msgheader[0] = linkedAddr;
		Msgheader[1] = protocolversion;
		Msgheader[2] = opType;
		Msgheader[3] = objectFlag;
		bos.write(Msgheader);
		byte[] header = bos.toByteArray();
		bos.close();			
		/******** 拼装消息体 **********/
		ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
		long curtime = System.currentTimeMillis();  //对时		
		bos1.write(long2byte(curtime));
		byte[] body = bos1.toByteArray();
		bos1.close();
		
		return setNetRadarMsg(header, body);
	
 }
 /**
  * 计算校验和
  * @param bytes
  * @return
  */
 public static long getCRC32Checksum(byte[] bytes) {
	    Checksum crc32 = new CRC32();
	    crc32.update(bytes, 0, bytes.length);
	    return crc32.getValue();
	}
 
 public static byte[] long2byte(long res) {
	 byte[] buffer = new byte[8];
	 for (int i = 0; i < 8; i++) {
	 int offset = 64 - (i + 1) * 8;
	 buffer[i] = (byte) ((res >> offset) & 0xff);
	 }
	 return buffer;
	 }

	 public static long byteArrayToLong(byte[] b){
	 long values = 0;
	 for (int i = 0; i < 8; i++) {
	 values <<= 8; values|= (b[i] & 0xff);
	 }
	 return values;
	 }

}
